package function;

import java.util.ArrayList;
import java.util.List;

import common.PostJson;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class SendAction {

	private static String GET_ORDERS_ALL = "http://106.15.43.138:8080/api/order/lists_new";
	
	//根据出发地获取历史最多和最新的寄件信息
	public static String getRecvInfo(JSONObject json){
		String aJson = PostJson.postJson(json, GET_ORDERS_ALL);
		JSONObject bJson = JSONObject.fromObject(aJson);
		JSONArray jaLists = bJson.getJSONArray("list");
		String Code = json.getString("lot_code");
		JSONArray recvList = new JSONArray();
		// 根据出发地的code，获取所有的目的地
		for (int i = 0; i < jaLists.size(); i++) {
			JSONObject joList = jaLists.getJSONObject(i);
			String lineId = joList.getString("line_id");
			String type = joList.getString("order_type");
			if (Code.equals(lineId.substring(0, 6)) && type.equals("2")) {
				JSONObject locations = joList.getJSONObject("locations");
				JSONObject end = locations.getJSONObject("end");
				JSONObject recvInfo = new JSONObject();
				recvInfo.put("name", end.getString("name"));
				recvInfo.put("phone", end.getString("phone"));
				recvList.add(recvInfo);
			}
		}
		if (recvList.size() == 0) {
			JSONObject message = new JSONObject();
			message.put("message", "未找到目的地");
			return message.toString();
		}
		List<String> recv = new ArrayList<>();
		List<String> newRecv = new ArrayList<>();
		// 定义endAdd的list
		JSONObject endAddress = new JSONObject();
		JSONObject latest = new JSONObject();
		latest.put("name", recvList.getJSONObject(0).getString("name"));
		latest.put("phone", recvList.getJSONObject(0).getString("phone"));
		endAddress.put("latest", latest);
		for (int i = 0; i < recvList.size(); i++) {
			recv.add(recvList.getJSONObject(i).getString("phone"));
		}
		newRecv = recv;
		int[] count = new int[newRecv.size()];
		// 计算各个元素数量
		for (int i = 0; i < newRecv.size(); i++)
			for (int j = 0; j < recv.size(); j++) {
				if (newRecv.get(i).equals(recv.get(j))) {
					count[i]++;
				}
			}
		int max = 0;
		int index = 0;
		for (int i = 0; i < newRecv.size(); i++) {
			if (count[i] > max) {
				max = count[i];
				index = i;
			}
		}
		JSONObject most = new JSONObject();
		most.put("name", recvList.getJSONObject(index).getString("name"));
		most.put("phone", recvList.getJSONObject(index).getString("phone"));
		endAddress.put("most", most);
		JSONArray other = new JSONArray();
		for (int i = 0; i < newRecv.size(); i++) {
			if (i != 0 && i != index) {
				JSONObject otherObj = new JSONObject();
				otherObj.put("name", recvList.getJSONObject(i).getString("name"));
				otherObj.put("phone", recvList.getJSONObject(i).getString("phone"));
				other.add(otherObj);
			}
		}
		endAddress.put("other", other);
		return endAddress.toString();
	}
}
